13. Class Variables

Class Variables

Your first task will be to declare the variables in your Matrix class. As a reminder, here is the general syntax for declaring a C++ class:

class Classname
{
    private:
        declare private variables;
        declare private functions;

    public:
        declare public variables;
        declare public functions;
};

The lines for actually declaring the variables are the same as any other C++ variable declaration:

datatype variablename;

The Matrix class has three private variables:

  • grid - a 2D float vector to hold the matrix values
  • rows - the number of rows in the matrix
  • columns - the number of columns in the matrix

The rows and columns variables should be declared as a size_type. A size_type variable holds the size of a vector.

If your vector holds integers, the size_type declaration looks like this:

std::vector<int>::size_type variablename;

If your vector holds floats, then the size_type declaration would look like this:

std::vector<float>::size_type variablename;

The value that goes inside the brackets <> is based on whatever the original vector declaration was. A size_type variable is actually an unsigned int. The size_type variable is guaranteed to be able to hold up to the maximum size of a float vector.

Fill out the header file below with the variable declarations. This quiz is not graded, but the answer is included below.

Start Quiz:

#include <vector>

// Header file for the Matrix class

/* 
**  TODO:
**    Declare the following private variables:
**      a 2D float vector variable called grid
**      a vector size_type variable called rows
**      a vector size_type variable called cols
*/

class Matrix 
{
    
    
    
    
    
};
#include <iostream>
#include <vector>
#include "matrix.h"

int main () {
    
    // TODO: Nothing to do here
    
    return 0;
}
// TODO: Nothing to do here

Solution

class Matrix 
{

        private:

            std::vector< std::vector<float> > grid;
            std::vector<float>::size_type rows;
            std::vector<float>::size_type cols;    
};

In the next step, you will declare your class functions and then define your class functions.